package com.iwinding.ladygg.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.iwinding.ladygg.bluetooth.bean.BleDevice;
import com.junkchen.blelib.BleService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 82218 on 2017/6/24.
 */

public class BluetoothManager {


    public static final int SERVICE_BIND = 1;
    public static final int SERVICE_SHOW = 2;

    private static BluetoothManager INSTANCE = new BluetoothManager();

    private Context mContext;

    private BleService mBleService = null;//蓝牙服务

    private String mConnRssi;//当前连接设备信号
    private String connDeviceName;//当前连接设备名称
    private String connDeviceAddress;//当前连接设备地址
    private List<BleDevice> deviceList;//设备列表

    private boolean mIsBind;
    private boolean mInitialize;

    private ServiceConnection serviceConnection;

    private Handler mHandler;

    public BluetoothManager() {
        deviceList = new ArrayList<BleDevice>();
        mHandler = new BleHandler();
        serviceConnection = new BleServiceConnection();
    }

    public static BluetoothManager getInstance() {
        return INSTANCE;
    }

    public List<BleDevice> getDeviceList() {
        return deviceList;
    }

    //初始化Context
    public void initContext(Context mContext) {
        this.mContext = mContext;
    }

    //初始化服务
    public void initBleService() {
        if (!mIsBind) {
            onBindService();
        }
    }

    /**
     * 绑定服务
     */
    private void onBindService() {
        if (mContext == null) {
            return;
        }
        try {
            Intent serviceIntent = new Intent(mContext, BleService.class);
            mContext.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        }catch (Exception e){

        }
    }

    /**
     * 解绑服务
     */
    public void unBindService() {
        if (mIsBind) {
            try {
                mContext.unbindService(serviceConnection);
            }catch (Exception e){

            }
            mBleService = null;
            mInitialize = false;
            mIsBind = false;
        }
    }

    public boolean isScanning() {
        if (mBleService != null)
            return mBleService.isScanning();
        return false;
    }

    /**
     * 扫描设备
     */
    public void scanDevice() {
        if (!mInitialize|| mBleService==null) {
            return;
        }
        //如果正在扫描，先停止扫描并清空设备列表
        if (isScanning()) {
            mBleService.scanLeDevice(false);
        }
        deviceList.clear();
        //然后进行扫描
        mBleService.scanLeDevice(true);
    }

    /**
     * 停止扫描
     */
    public void stopScanDevice() {
        if (!mInitialize|| mBleService==null) {
            return;
        }
        //如果正在扫描，先停止扫描并清空设备列表
        if (isScanning()) {
            mBleService.scanLeDevice(false);
        }
    }

    /**
     * 连接设备
     *
     * @param address
     */
    public void connDevice(String address) {
        if (TextUtils.isEmpty(address)) {
            return;
        }
        if (!mInitialize|| mBleService==null) {
            return;
        }
//        if (mBleService.isConnect() && !TextUtils.equals(connDeviceAddress, address)) {
//            mBleService.disconnect();
//        }
        mBleService.connect(address);
        connDeviceAddress = address;
    }

    /**
     * 断开连接
     */
    public void disconnDevice() {
        if (!mInitialize|| mBleService==null) {
            return;
        }
        if (mBleService.isConnect())
            mBleService.disconnect();
    }

    public BluetoothGatt getConnBluetoothGatt() {
        if (!mInitialize|| mBleService==null) {
            return null;
        }
        return mBleService.getBluetoothGatt();
    }

    /**
     * 设置通知
     *
     * @param characteristic
     * @param enabled
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (!mInitialize|| mBleService==null) {
            return;
        }
        if (mBleService.isConnect())
            mBleService.setCharacteristicNotification(characteristic, enabled);
    }

    /**
     * 写入数据
     *
     * @param serviceUUID
     * @param characteristicUUID
     * @param value
     */
    public void writeData(String serviceUUID, String characteristicUUID, byte[] value) {
        if (!mInitialize|| mBleService==null) {
            return;
        }
        if (mBleService.isConnect())
            mBleService.writeCharacteristic(serviceUUID, characteristicUUID, value);
    }

    class BleServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBleService = ((BleService.LocalBinder) service).getService();
            mIsBind = true;
            mInitialize = mBleService.initialize();
            if (mInitialize) {
                mHandler.sendEmptyMessage(SERVICE_BIND);
                if (mBleService.enableBluetooth(true)) {
                    Toast.makeText(mContext, "Bluetooth was opened", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(mContext, "not support Bluetooth", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBleService = null;
            mInitialize = false;
            mIsBind = false;
        }
    }

    class BleHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SERVICE_BIND:
                    setBleServiceListener();
                    scanDevice();//绑定服务后开始搜索
                    break;
                case SERVICE_SHOW:
                    break;
            }
        }
    }

    /**
     * 设置监听
     */
    private void setBleServiceListener() {
        if (!mInitialize || mBleService==null) {
            return;
        }
        //监听扫描设备
        mBleService.setOnLeScanListener(new BleService.OnLeScanListener() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                if(mBleService==null){
                    return;
                }
                BleDevice bleDevice = new BleDevice();
                bleDevice.deviceName = device.getName();
                bleDevice.deviceAddress = device.getAddress();
                bleDevice.deviceRssi = String.valueOf(rssi);
                bleDevice.isConnect = false;
                if (mBleService.getConnectDevice()!=null) {
                    BluetoothDevice bluetoothDevice = mBleService.getConnectDevice();
                    String connectAdr = bluetoothDevice.getAddress();
                    if (!TextUtils.isEmpty(connectAdr) && bluetoothDevice.getAddress().equals(device.getAddress())) {
                        bleDevice.isConnect = true;
                    }
                }
                deviceList.add(bleDevice);
                if (mOnBleDeviceLinster != null) {
                    mOnBleDeviceLinster.obtainDevices(deviceList);
                }
            }
        });
        //回调信号
        mBleService.setOnReadRemoteRssiListener(new BleService.OnReadRemoteRssiListener() {
            @Override
            public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                mConnRssi = String.valueOf(rssi);
            }
        });
    }

    private OnBleDeviceLinster mOnBleDeviceLinster = null;

    public void setmOnBleDeviceLinster(OnBleDeviceLinster mOnBleDeviceLinster) {
        this.mOnBleDeviceLinster = mOnBleDeviceLinster;
    }

    public interface OnBleDeviceLinster {
        void obtainDevices(List<BleDevice> devices);

    }

    public interface OnBleManageListener extends BleService.OnConnectionStateChangeListener, BleService.OnServicesDiscoveredListener {

    }

    public void setOnBleManageListener(OnBleManageListener listener) {
        if (!mInitialize)
            return;
        //设备连接回调
        if (mBleService != null && listener != null)
            mBleService.setOnConnectListener(listener);
        //服务特性回调
        if (mBleService != null && listener != null)
            mBleService.setOnServicesDiscoveredListener(listener);
    }

    public void setOnDataAvailableListener(BleService.OnDataAvailableListener listener) {
        if (!mInitialize)
            return;
        if (mBleService != null && listener != null)
            mBleService.setOnDataAvailableListener(listener);
    }


}
